package com.test.system.admin.service;

import com.test.system.admin.dao.ScriptDAO;
import com.test.system.admin.pojo.Script;
import com.test.system.admin.quartz.QuartzUtil;
import com.test.system.admin.util.AdminConstants;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.List;

@Service
public class ScriptService {
    @Autowired
    private ScriptDAO scriptDAO;

    @PostConstruct//在bean初始化成功之后执行的
    private void init() {
        Script criteria = new Script();
        criteria.setStatus(AdminConstants.SCRIPT_STATUS_RUNNING);
        List<Script> scripts = scriptDAO.getScriptList(criteria);
        for (Script script : scripts) {
            String name = script.getName();
            try {
                Class jobClass = Class.forName(name);
                QuartzUtil.addJob(name, name, name, name, script.getCron(), jobClass);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }


    public List<Script> getScriptList(Script script) {
        return scriptDAO.getScriptList(script);
    }

    public void updateScript(Script script) {
        scriptDAO.updateScript(script);

    }

    public void addScript(Script script) {
        scriptDAO.addScript(script);
    }

    public void doResumeScript(Integer id) {
        Script script = scriptDAO.getScriptById(id);
        script.setStatus(AdminConstants.SCRIPT_STATUS_RUNNING);
        scriptDAO.updateScript(script);
        String name = script.getName();
        int status = QuartzUtil.getJobStatus(name, name);
        if (status == 2) {//quartz中有任务，并且是暂停状态
            QuartzUtil.resumeJob(name, name);
        } else {
            try {
                Class jobClass = Class.forName(name);
                QuartzUtil.addJob(name, name, name, name, script.getCron(), jobClass);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    public void doPauseScript(Integer id) {
        Script script = scriptDAO.getScriptById(id);
        script.setStatus(AdminConstants.SCRIPT_STATUS_PAUSE);
        scriptDAO.updateScript(script);
        QuartzUtil.pauseJob(script.getName(), script.getName());
    }
}
